package com.sinosoft.common.encrypt.filter;

import cn.hutool.core.io.IoUtil;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.sinosoft.common.core.constant.Constants;
import com.sinosoft.common.core.constant.HeaderConstants;
import com.sinosoft.common.core.enums.ErrorCodeEnum;
import com.sinosoft.common.core.exception.GlobalAuthException;
import com.sinosoft.common.core.utils.StringUtils;
import com.sinosoft.common.encrypt.properties.ApiDecryptProperties;
import com.sinosoft.common.encrypt.utils.CryptoUtils;
import jakarta.servlet.ReadListener;
import jakarta.servlet.ServletInputStream;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletRequestWrapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.MediaType;

import java.io.BufferedReader;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.nio.charset.StandardCharsets;

/**
 * JWT安全模式请求体包装类
 * 使用SM2/SM4加密方式 (SAFE_MODE=1)
 *
 * @author zzf
 */
@Slf4j
public class JwtSafeModeRequestWrapper extends HttpServletRequestWrapper {

    private final byte[] body;

    public JwtSafeModeRequestWrapper(HttpServletRequest request, ApiDecryptProperties properties) throws IOException {
        super(request);
        // 验证SM2私钥配置
        if (StringUtils.isBlank(properties.getSm2PrivateKey())) {
            throw new GlobalAuthException(ErrorCodeEnum.PARAM_EMPTY, "SM2私钥未配置", "JWT安全模式需要配置SM2私钥");
        }
        request.setCharacterEncoding(Constants.UTF8);
        byte[] readBytes = IoUtil.readBytes(request.getInputStream(), false);
        String requestBody = new String(readBytes, StandardCharsets.UTF_8);
        if (requestBody != null && requestBody.startsWith("\"") && requestBody.endsWith("\"")) {
            requestBody = requestBody.substring(1, requestBody.length() - 1);
        }
        // 获取并解密 SM4 密钥
        String encryptedKey = request.getHeader(HeaderConstants.ENCRYPT_KEY);
        if (StringUtils.isBlank(encryptedKey)) {
            throw new GlobalAuthException(ErrorCodeEnum.PARAM_EMPTY, "加密密钥不能为空", "安全模式下必须提供加密密钥");
        }
        try {
            // 解密 SM4 密钥
            String sm4Key = CryptoUtils.decryptSm4Key(encryptedKey, properties.getSm2PrivateKey());
            // 解密请求体
            requestBody = CryptoUtils.decryptBody(requestBody, sm4Key);
        } catch (GlobalAuthException e) {
            throw e;
        } catch (Exception e) {
            log.error("JWT安全模式请求解密失败: {}", e.getMessage());
            throw new GlobalAuthException(ErrorCodeEnum.SYSTEM_INTERNAL_ERROR, "请求解密失败", e.getMessage());
        }
        body = requestBody.getBytes(StandardCharsets.UTF_8);
    }

    @Override
    public BufferedReader getReader() {
        return new BufferedReader(new InputStreamReader(getInputStream()));
    }

    @Override
    public int getContentLength() {
        return body.length;
    }

    @Override
    public long getContentLengthLong() {
        return body.length;
    }

    @Override
    public String getContentType() {
        return MediaType.APPLICATION_JSON_VALUE;
    }

    @Override
    public ServletInputStream getInputStream() {
        final ByteArrayInputStream bais = new ByteArrayInputStream(body);
        return new ServletInputStream() {
            @Override
            public int read() {
                return bais.read();
            }

            @Override
            public int available() {
                return body.length;
            }

            @Override
            public boolean isFinished() {
                return false;
            }

            @Override
            public boolean isReady() {
                return false;
            }

            @Override
            public void setReadListener(ReadListener readListener) {
                // 不需要实现
            }
        };
    }
}
